
let socketLinks = { // socket链接列表，一个链接可以配置多个路由规则
    // "" : {
    //     routers : { //路由规则
    //         /请求前缀 : { 
    //             host : "host地址", 
    //             port : "端口号", 
    //             type : "规则类型：http【转发http请求】file【开放本地资源】", 
    //             flowSize : "流量"
    //        }
    //     }
    // }
}

/**
 * 添加socket链接
 * @param {string} socketId
 */
socketLinks.addSocket = function (socketId){
    socketLinks[socketId] = {
        id : socketId,
        routers : {}
    }
}

/**
 * 删除socket链接
 * @param {string} socketId
 */
socketLinks.delSocket = function (socketId){
    delete socketLinks[socketId]
}

/**
 * 查找路由规则
 * @param {string} path
 * @returns {object} {socketId, ...router}
 */
socketLinks.findRouter = function (path){
    socketFor : for (let socketId in socketLinks) {
        routerFor : for (let routerId in socketLinks[socketId].routers) {

            if(path != routerId){
                continue routerFor
            }

            return {
                socketId,
                ...socketLinks[socketId].routers[routerId]
            }
        }
    }
}

/**
 * 添加路由规则
 * @param {string} socketId
 * @param {string} path
 * @param {object} { host : "host地址", port : "端口号", type : "规则类型：http【转发http请求】file【开放本地资源】", flowSize : "流量"}
 * @returns {string} 错误提示
 */
socketLinks.addRouter = function (socketId, path, route){
    let router = socketLinks.findRouter(path)
    if(router){
        return "路由已存在"
    }

    route.flowSize = 0
    route.host = route.host || '127.0.0.1'
    route.port = route.port || '8080'

    socketLinks[socketId].routers[path] = route
}

/**
 * 删除路由规则
 * @param {string} socketId
 * @param {string} path
 */
socketLinks.delRouter = function (socketId, path){
    delete socketLinks[socketId].routers[path]
}


module.exports = socketLinks